import React from 'react'
import axios from 'axios'
import TodoList from './comps/todo-list'

class TodoPage extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            todoList: [],
            showTooltip: false // 控制 tooltip 的显示隐藏
        }
    }

    componentDidMount() {
        // 获取所有的 todolist
        this._getTodoList();

        /*fetch('/api/html')
          .then((res) =>{
            return res.json();
          })
          .then((res) =>{
            console.log(res)
          })
        }*/
    }

    // 获取 todolist
    _getTodoList() {
        const that = this;
        axios.get('/api/todoItems').then((res) => {
            const todoList = res.data;
            console.log("获取全部");
            console.log(todoList);
            that.setState({ todoList })
        }).catch((err) => {
            console.log(err);
        })
    }

    // 添加 todo
    _onNewItem(newItem) {
        const that = this;
        axios.post('/api/todoItems', {
            newItem
        }).then((res) => {
            console.log("添加成功");
            let todoList = res.data;
            console.log(todoList);
            todoList = that.todoSort(todoList);
            that.setState({
                todoList
            })
        }).catch((err) => {
            console.log(err);

        })
    }

    // 删除 todo
    _onDeleteItem(id) {
            const that = this;
            axios.delete(`/api/todoItems/${id}`)
                .then(res => {
                    console.log("删除成功！！！！");
                    const todoList = res.data;
                    console.log(todoList);
                    that.setState({
                        todoList
                    });
                })
                .catch(err => {
                    console.log(err);
                })
        }
        // change todo
    _onCheckItem(id) {
        const that = this;
        const postData = {
            'done': true
        };
        axios.patch(`/api/todoItems/${id}`, {
            postData
        }).then(res => {
            if (res.status === 200) {
                console.log("更新成功！！！！");
                const todoList = res.data;
                console.log(todoList);
                that.setState({
                    todoList
                });
            }
        }).catch(err => {
            console.log(err);
        })
    }

    // 对 todolist 进行逆向排序（使新录入的项目显示在列表上面）
    todoSort(todoList) {
        todoList.reverse();
        return todoList;
    }

    // 提交表单操作
    handleSubmit(event) {

        event.preventDefault();
        // 表单输入为空验证
        if (this.refs.content.value === "") {
            this.refs.content.focus();
            this.setState({
                showTooltip: true
            });
            return;
        }
        // 生成参数
        var newItem = {
            'content': this.refs.content.value,
            'date': (new Date().getMonth() + 1) + "/" +
                new Date().getDate() + " " +
                new Date().getHours() + ":" +
                new Date().getMinutes() + ":" +
                new Date().getSeconds(),
            'done': false
        };
        // 添加 todo
        this._onNewItem(newItem)
            // 重置表单
        this.refs.todoForm.reset();
        // 隐藏提示信息
        this.setState({
            showTooltip: false,
        });
    }

    render() {
        return ( <
            div className = "container" >
            <
            h2 className = "header" > Todo List < /h2> <
            form className = "todoForm"
            ref = "todoForm"
            onSubmit = { this.handleSubmit.bind(this) } >
            <
            div className = "todo-ipt-wrap clear" >
            <
            input ref = "content"
            maxLength = "100"
            type = "text"
            placeholder = "Type content here..."
            className = "todoContent" / >
            <
            div className = "todoBtn"
            onClick = { this.handleSubmit.bind(this) } > 添加 < /div> < /
            div > {
                this.state.showTooltip &&
                <
                span className = "tooltip" > Content is required! < /span>
            } <
            /form> <
            TodoList todoList = { this.state.todoList }
            onCheckItem = { this._onCheckItem.bind(this) }
            onDeleteItem = { this._onDeleteItem.bind(this) }
            /> < /
            div >
        )
    }
}

export default TodoPage;